package br.com.vilababy.sigvb.filters;

import java.util.regex.Pattern;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import br.com.vilababy.sigvb.SIGVBUtil;
import br.com.vilababy.sigvb.constantes.PaginaEnum;
import br.com.vilababy.sigvb.constantes.SIGVBEnum;

public class AutenticacaoFilter implements PhaseListener {
	
	/**
	 * @author Diego Patrick da Silva Santos
	 */
	private static final long serialVersionUID = 1L;
	

	@Override
	public void afterPhase(PhaseEvent event) {
		
		FacesContext contexto = event.getFacesContext();
		String viewId = SIGVBUtil.getPath().concat(contexto.getViewRoot().getViewId());
		
		boolean acessoRestrito = Pattern.matches(SIGVBEnum.RESTRICTION_PATTERN.getValor(), viewId);
		Object usuario = contexto.getExternalContext().getSessionMap().get(SIGVBEnum.USUARIO_LOGADO.getValor());
		NavigationHandler navigator = contexto.getApplication().getNavigationHandler();
		
		if (acessoRestrito && usuario == null && !verificarRequisicaoLogin(viewId)) {
			navigator.handleNavigation(contexto, null, PaginaEnum.LOGIN.getValor());
			contexto.renderResponse();
		} else if (usuario != null && viewId.contains(PaginaEnum.LOGIN.getValor())) {
			navigator.handleNavigation(contexto, null, PaginaEnum.PRINCIPAL.getValor());
			contexto.renderResponse();
		}
		
	}
	
	private boolean verificarRequisicaoLogin(String viewId) {
		if(viewId.equalsIgnoreCase(SIGVBUtil.getPath().concat(PaginaEnum.LOGIN.getValor())))
			return true;
		return false;
	}

	@Override
	public void beforePhase(PhaseEvent event) {
		
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
